import { addChargeCostApi, editChargeCostApi } from "@/api/waybillManagement/businessWaybill/waybillQuotation";
import FormHook from "@/hook/formHook";
import { GeneraDataType } from "@/interface";
import { message } from "ant-design-vue";
export default function OperationHook(state: GeneraDataType) {
  const { formState, formDataRef, emit, passData, loading, type } = state;
  const { resetFields } = FormHook({ formState });
  const onFinish = () => {
    const params = {
      ...formState,
      waybillNum: passData.value.waybillNum
    };

    loading.value = true;
    addChargeCostApi(params)
      .then((res: any) => {
        const { code } = res;
        if (code === 200) {
          message.success("操作成功!");
          emit("addChargeSubmit");
        }
      })
      .finally(() => (loading.value = false));
  };

  const submitHandle = () => {
    formDataRef.value.validate().then(() => {
      let requestFn;
      const params = {
        ...formState,
        waybillNum: passData.value.waybillNum
      };
      if (type.value === 1) {
        requestFn = addChargeCostApi;
      } else {
        requestFn = editChargeCostApi;
        params.id = passData.value.id;
      }
      loading.value = true;
      requestFn(params)
        .then((res: any) => {
          const { code } = res;
          if (code === 200) {
            message.success("操作成功!");
            emit("addChargeSubmit");
          }
        })
        .finally(() => (loading.value = false));
    });
  };

  const onFinishFailed = (errorInfo: any) => {
    console.log("Failed:", errorInfo);
  };
  const resetHandle = () => {
    resetFields();
    formDataRef.value.clearValidate();
    emit("update:visible", false);
  };
  const filterOption = (input: string, option: any) => {
    return String(option.value).toLowerCase().indexOf(String(input).toLowerCase()) >= 0;
  };
  return {
    onFinish,
    onFinishFailed,
    resetHandle,
    resetFields,
    submitHandle,
    filterOption
  };
}
